<template>
  <van-row  justify="center" style="margin-top:30px; margin-bottom: 30px;">
    <van-image
        round
        width="180"
        height="180"
        :src=cuteImage
        style="background-position:center"
    />
  </van-row>

  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
          v-model="registerForm.userAccount"
          name="userAccount"
          label="账号"
          placeholder="请输入账号"
          :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
          v-model="registerForm.userPassword"
          type="password"
          name="userPassword"
          label="密码"
          placeholder="请输入密码"
          :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
          v-model="registerForm.checkPassword"
          type="password"
          name="checkPassword"
          label="确认密码"
          placeholder="再次输入密码"
          :rules="[{ validator: validatorMessage, message: '两次输入密码不一致' }]"

      />
      <van-field
          v-model="registerForm.planetCode"
          name="planetCode"
          label="星球编号"
          placeholder="请输入星球编号"
          :rules="[{ required: true, message: '请输入星球编号' }]"
      />
    </van-cell-group>

<!--    <div style="margin: 16px;">-->
<!--      <van-button round block type="primary" native-type="submit">-->
<!--        注册-->
<!--      </van-button>-->
<!--    </div>-->

    <div style="margin: 20px">
      <van-button style="margin-top: 10px; background-color: #3D94E5; width: 200px; margin-left: 65px" round block native-type="submit"
                  to="/user/register">
        注 册
      </van-button>
    </div>
  </van-form>
</template>

<script setup lang="ts">
import {useRoute, useRouter} from "vue-router";
import {ref} from "vue";
import myAxios from "../plugins/myAxios";
import {Toast} from "vant";
import cuteImage from "../assets/images/cute1.jpg";

const router = useRouter();
const route = useRoute();

// const userAccount = ref('');
// const userPassword = ref('');
// const checkPassword = ref('');
// const planetCode = ref('');

const registerForm = ref({
  userAccount: '',
  userPassword: '',
  checkPassword: '',
  planetCode: '',
})

// 校验函数可以直接返回一段错误提示
const validatorMessage = () => {
  return registerForm.value.checkPassword.value === registerForm.value.userPassword.value;
};

const onSubmit = async () => {
  const res = await myAxios.post('/user/register', registerForm.value)
  console.log(res, '用户注册');
  if (res.code === 0 && res.data) {
    Toast.success('注册成功');
    registerForm.value = {
      userAccount: '',
      userPassword: '',
      checkPassword: '',
      planetCode: '',
    }
    // 跳转到登录页面
    // const redirectUrl = '/user/login';
    // window.location.href = redirectUrl;
    router.replace({
      path: '/user/login',
    })
  } else {
    Toast.fail(res.description);
  }
};

</script>

<style scoped>

</style>